package com.leetcode.partition6;

import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2021/8/26 10:30
 */
public class LC583两个字符串的删除操作 {

    public static int minDistance(String word1, String word2) {
        return dynamicProgramming(word1, word2);
    }

    public static void main(String[] args) {
        System.out.println(minDistance("a", "b"));
//        System.out.println(dynamicProgramming1("abcd", "bd"));
    }

    /**
     * dp[i][j]表示word1[i-1]和word2[j-1]达到相等需要删除的元素个数
     * 状态转移方程式：当word1[i-1]==word2[j-1]时，dp[i][j]=dp[i-1][j-1]；当word1[i-1]!=word2[j-1]时，分为三种情况，
     * 情况1：删除word1[i-1]，最少操作次数为dp[i-1][j]+1
     * 情况2：删除word2[j-1]，最少操作次数dp[i][j-1]+1
     * 情况3：同时删除word1[i-1]和word2[j-1]，
     * 最少操作次数dp[i-1][j-1]+2；dp[i][j] = Math.min(dp[i-1][j]+1, Math.min(dp[i][j-1]+1, dp[i-1][j-1]+2))
     */
    private static int dynamicProgramming(String word1, String word2) {
        int m = word1.length(), n = word2.length();
        int[][] dp = new int[m + 1][n + 1];
        //初始化，不论是word1还是word2，和空串相比都需要全部删除
        for (int i = 1; i <= m; i++) dp[i][0] = i;
        for (int j = 1; j <= n; j++) dp[0][j] = j;
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]) + 1, dp[i - 1][j - 1] + 2);
                }
            }
        }
        Arrays.stream(dp).forEach(val -> System.out.println(Arrays.toString(val)));
        return dp[m][n];
    }
}
